package com.caration.shell.config;

import java.io.File;
import java.io.IOException;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;

import com.caration.shell.Home;
import com.caration.shell.R;

public class ImportAyncTask extends AsyncTask<Object, Integer, String> {
	private final ProgressDialog mProgressDialog;
	private Context mContext;

	public ImportAyncTask(Context context) {
		mContext = context;
		mProgressDialog = new ProgressDialog(context);
	}

	@Override
	protected String doInBackground(Object... params) {
		String result = "";
		boolean success = true;
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			File backDBFile = new File(ConfigManger.DB_EXTENAL_PATH);
			if (!backDBFile.exists()) {
				return mContext.getResources().getString(
						R.string.dbfile_not_found);
			}
			if (!backDBFile.canRead()) {
				return mContext.getResources().getString(
						R.string.dbfile_not_readable);
			}

			try {
				File DBFile = new File(ConfigManger.DB_INTERNAL_PATH);
				if (DBFile.exists())
					DBFile.delete();
				DBFile.createNewFile();
				ConfigManger.transferFile(backDBFile, DBFile);

				File settingsFile = new File(ConfigManger.CONFIG_EXTENAL_PATH);
				if (settingsFile.exists()) {
					File configFile = new File(
							ConfigManger.CONFIG_INTERNAL_PATH);
					if (configFile.exists())
						configFile.delete();
					configFile.createNewFile();
					ConfigManger.transferFile(settingsFile, configFile);
				}
			} catch (IOException e) {
				e.printStackTrace();
				success = false;
			}
			if (success) {
				Home.getInstance().restartDelayed();
				result = mContext.getResources().getString(
						R.string.dbfile_import_success);
			} else {
				result = mContext.getResources().getString(
						R.string.dbfile_import_error);
			}
		} else {
			result = mContext.getResources().getString(
					R.string.import_export_sdcard_unmounted);
		}
		return result;
	}

	@Override
	protected void onPreExecute() {
		mProgressDialog.setMessage(mContext.getResources().getString(
				R.string.dbfile_import_dialog));
		mProgressDialog.show();
	}

	protected void onPostExecute(String result) {
		if (mProgressDialog.isShowing())
			mProgressDialog.dismiss();
		Toast.makeText(mContext, result, Toast.LENGTH_SHORT).show();
	};
}
